package com.ltc.smstimer.timer;

import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.Toast;

public class AlarmAlert extends Activity{
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Toast.makeText(AlarmAlert.this,"binggou~It's time to send message",Toast.LENGTH_LONG).show(); 
        //获取传递进来的信息
        SharedPreferences sp = getSharedPreferences("message",0);
        String address = sp.getString("phoneNumber", "");
		String messageText = sp.getString("messageText", "");
		
		//调用发送短信的方法	
		//循环发送实现群发
		if(address.trim().length() != 0 && messageText.trim().length() != 0){
			//拆分短信
			String[] temp = address.split(",");
			int k = temp.length;
			
			//发送短信
			Toast.makeText(getApplicationContext(),"--总计发送给"+k+"个联系人",Toast.LENGTH_LONG).show();
			for(int i =0; i < k; ++i ){
				try{
					Toast.makeText(getApplicationContext(),"正在向"+temp[i]+"发送",Toast.LENGTH_LONG).show();
					SmsManager sms = SmsManager.getDefault(); 
					PendingIntent pi = PendingIntent.getBroadcast(AlarmAlert.this,0,new Intent(),0);
					//将短信分割
					List<String> texts = sms.divideMessage(messageText);
					for(String text:texts){
						sms.sendTextMessage(temp[i],null,messageText,pi,null);  
					}
					Toast.makeText(getApplicationContext(),"向"+temp[i]+"发送成功",Toast.LENGTH_LONG).show(); 
				}catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(getApplicationContext(),"向发送"+temp[i]+"失败",Toast.LENGTH_LONG).show();
				}
				//将短信保存在发件箱

				try{
					ContentValues values = new ContentValues(); 
					values.put("address", temp[i]); 
					values.put("body", messageText); 
					getContentResolver().insert(Uri.parse("content://sms/sent"), values); 
					Toast.makeText(getApplicationContext(),"短信已保存到系统数据库",Toast.LENGTH_LONG).show();
				}catch (Exception e) {
				    e.printStackTrace();
					Toast.makeText(getApplicationContext(),"短信未保存到系统数据库中",Toast.LENGTH_LONG).show();
				}

			}
			
			
		}else{
			Toast.makeText(getApplicationContext(),"联系人或短信内容不能为空",Toast.LENGTH_LONG).show();
		}
		
		Toast.makeText(AlarmAlert.this,"send success",Toast.LENGTH_LONG).show(); 
		AlarmAlert.this.finish();
	}
}
